package com.iflytek.jzcpx.procuracy.cont.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.iflytek.jzcpx.procuracy.cont.common.constants.CacheKeyPrefixConstants;
import com.iflytek.jzcpx.procuracy.cont.model.PrometheusQo;
import com.iflytek.jzcpx.procuracy.cont.service.PromethusService;
import com.iflytek.jzcpx.procuracy.cont.service.RedisDataService;
import cn.hutool.core.util.StrUtil;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @author iFLYREC
 *
 */
@Service
public class PromethusServiceImpl implements PromethusService {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private RedisDataService redisDataService;

	private static final ExecutorService pool = Executors.newFixedThreadPool(100);

	// @Value("${argue.on}")
	// private String argueOn;

	// @Value(("${prometheus.url}"))
	// private String prometheusUrl;

	@Autowired
	private RestTemplate restTemplate;

	/**
	 * 发送counter类型的数据到promethus，区分法院信息
	 * 
	 * @param dossierId
	 * @param value
	 * @param tags
	 */
	@Override
	public void counterTypeWithCourt(Integer dossierId, String metric, int value, String tags) {

		String argueOn = "0";

		String prometheusUrl = "";

		// 监控平台开关
		if (argueOn.equals("0")) {
			return;
		}
		pool.execute(() -> {
			String court = redisDataService.getArgueData(CacheKeyPrefixConstants.ARGUE_DATA + dossierId, "endPoint");
			String tagStr = StrUtil.format("court,{},{}", court, tags);
			try {
				PrometheusQo prometheusQo = new PrometheusQo();
				prometheusQo.setMetric(metric);
				prometheusQo.setTags(tagStr);
				prometheusQo.setValue(value);
				restTemplate.postForObject(prometheusUrl, prometheusQo, String.class);
				logger.info("法院：{}, 指标名称: {}，value：{}, tags: {}", court, metric, value, tagStr);
			} catch (Exception e) {
				logger.error("指标名称 {} 埋点异常，异常为：{}", metric, e);
			}
		});
	}

	/**
	 * 发送counter类型的数据到promethus，不区分法院信息
	 * 
	 * @param dossierId
	 * @param value
	 * @param tags
	 */
	@Override
	public void counterType(Integer dossierId, String metric, int value, String tags) {

		String argueOn = "0";

		String prometheusUrl="";
		// 监控平台开关
		if (argueOn.equals("0")) {
			return;
		}
		pool.execute(() -> {
			try {
				PrometheusQo prometheusQo = new PrometheusQo();
				prometheusQo.setMetric(metric);
				prometheusQo.setTags(tags);
				prometheusQo.setValue(value);
				restTemplate.postForObject(prometheusUrl, prometheusQo, String.class);
				logger.info("指标名称: {} ，value：{}, tags: {}", metric, value, tags);
			} catch (Exception e) {
				logger.error("指标名称 {} 埋点异常，异常为：{}", metric, e);
			}
		});
	}

}
